

<template>
  <view class="Mall4j">
    <view class="promotionProd">
      <!-- 搜索框 -->
      <view class="pd-seach">
        <input type="text" :placeholder="i18n.enterProductName" confirm-type="search" @input="onProdNameInput" @confirm="onProdNameSearch"></input>
        <view class="pd-seach-icon">
          <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/sousuo.png" />
        </view>
      </view>

      <!--头部导航tab -->
      <view class="pd-tab">
        <view class="pd-tab-list">
          <!-- <view class="tab-item {{sort==0 && (orderBy==1?'down':'up')}}" bindtap='onTabTouch' data-sort='0'>佣金</view> -->
          <view :class="'tab-item ' + (sort==1 && (orderBy==1?'down':'up'))" data-sort="1" @tap="onTabTouch">{{ i18n.newest }}</view>
          <view :class="'tab-item ' + (sort==2 && (orderBy==1?'down':'up'))" data-sort="2" @tap="onTabTouch">{{ i18n.sales }}</view>
          <view :class="'tab-item ' + (sort==3 && (orderBy==1?'down':'up'))" data-sort="3" @tap="onTabTouch">{{ i18n.price }}</view>
        </view>
      </view>

      <view class="pd-main">
        <!-- 商品项 -->
        <view v-for="(item, prodId) in records" :key="prodId" class="pd-item">
          <view class="pd-item-top">
            <view class="pd-item-left border_radius_23">
              <image :src="item.pic" />
            </view>
            <view class="pd-item-right">
              <view class="pd-item-tit">{{ item.prodName }}</view>
              <view class="pd-item-price price">
                <text class="font_size_20">￥</text><text class="font_size_25">{{ wxs.toPrice(item.price) }}</text>
              </view>
              <view class="pd-item-info">
                <text class="rate">{{ i18n.expectedEarn }} {{ item.awardNumber }}{{ item.awardProportion==0?'%':i18n.yuan }}</text>
                <view class="pd-item-btm">
                  <view class="btn" :data-prodid="item.prodId" :data-prodname="item.prodName" :data-pic="item.pic" @tap="onShowShare">{{ i18n.shareIt }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <!-- 商品项 end -->

      </view>
      <view v-if="records.length==0" class="empty">{{ emptyMsg }}</view>
      <view v-if="totalPage>1" class="loading">{{ loadingMsg }}</view>

    </view>

    <!-- 分享弹窗 -->
    <view v-if="shareShow" class="promo-share">
      <view class="promo-main">
        <view class="promo-icons-close" @tap="closeEarn">
          <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/close.png" />
        </view>
        <view class="promo-tit">
          <title>{{ i18n.shareFriendsNow }}</title>
        </view>
        <view class="promo-desc">
          <text>{{ i18n.shareFriendsTips1 }}</text>
        </view>
        <view class="promo-icons">
          <!-- #ifdef H5 -->
          <button v-if="isWechat" class="promo-img1" @tap="onShareWay">
            <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/weixin.png" />{{ i18n.weChat }}
          </button>
          <!-- #endif -->
          <!-- #ifdef MP -->
          <button class="promo-img1" open-type="share">
            <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/weixin.png" />{{ i18n.weChat }}
          </button>
          <!-- #endif -->
          <view class="promo-img1" @tap="genWeixinCode">
            <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/erweima.png" />{{ i18n.QRCode }}
          </view>
        </view>
      </view>
    </view>
    <!-- 分享弹窗 end -->

    <!-- 二维码弹窗 -->
    <view v-if="wxCodeShow" class="code-popup">
      <view class="code-main">
        <view class="close-v" @tap.stop="closeCodePopup">
          <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/close.png" class="close-png" />
        </view>
        <view class="code-v">
          <image :src="shareWxCode" class="wx-code" />
        </view>
        <!-- #ifndef H5 -->
        <view class="code-txt" @tap="downloadImg">{{ i18n.saveAlbum }}</view>
        <!-- #endif -->
      </view>
    </view>
    <!-- 二维码弹窗 end -->

    <!-- 引导分享蒙版 -->
    <view v-if="guideShare" class="guide-share-mask">
      <view class="mask" />
      <view class="close" @tap="guideShare=false">
        <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/close-white.png" mode="" />
      </view>
      <view class="guide-content">
        <view class="share-img">
          <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/shareIcon.png" />
        </view>
        <view class="share-word">
          <view class="big-word">{{ i18n.shareFriendsNow }}</view>
          <view class="small-word">{{ i18n.shareFriendsTips2 }}</view>
        </view>
      </view>
    </view>
    <!-- 引导分享蒙版 end -->
  </view>
</template>

<script module="wxs" lang="wxs" src="../../wxs/number.wxs"></script>

<script>
var http = require("../../utils/http.js");
var config = require("../../utils/config.js");
var Qr = require('../../utils/wxqrcode.js');
import Wechat from "../../utils/wechat.js";
export default {
  data () {
    return {
      isWechat: false, //是否为微信环境
      records: [],
      shareShow: false,
      wxCodeShow: false,
      shareProdId: 0,
      shareProdName: "",
      sharePic: "",
      shareWxCode: "",
      //分享商品微信二维码
      loadingMsg: "",
      emptyMsg: "",
      totalPage: 1,
      pageNum: 1,
      prodName: "",
      //搜索的名称
      orderBy: 1,
      //排序(0升序 1降序) 默认1
      sort: 1, //排序(0 佣金排序 1时间排序 2销量排序 3价格排序) 默认1
      path: '', // 链接
      guideShare: false, // 引导蒙版
    };
  },

  components: {},
  props: {},

  computed: {
    i18n () {
      return this.$t('index')
    }
  },

  onShow: function () {
    //头部导航标题
    uni.setNavigationBarTitle({
      title: this.i18n.promoteGoods
    });

    this.loadingMsg = this.i18n.loading
    this.getDisInfo()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // #ifdef H5
    this.isWechat = Wechat.isWechat()
    // #endif
    this.loadPageData(1);
    this.getShareLink()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadPageData(1);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.pageNum < this.totalPage) {
      this.loadPageData(this.pageNum + 1);
    }
  },

  /**
   * 用户点击转发
   */
  // #ifdef MP-WEIXIN
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      var cardno = wx.getStorageSync("distCardNo");
      return {
        title: this.shareProdName,
        path: '/pages/prod/prod?prodid=' + this.shareProdId + '&cardno=' + cardno,
        imageUrl: this.sharePic
      };
    }
  },
  // #endif

  methods: {
    //加载分页数据
    loadPageData: function (pageNum) {
      var ths = this;
      http.request({
        url: "/p/distribution/prod/page",
        method: "GET",
        data: {
          shopId: 1,
          current: pageNum,
          orderBy: this.orderBy,
          prodName: this.prodName,
          size: 20,
          sort: this.sort
        },
        callBack: res => {
          uni.hideLoading();
          var records = [];

          if (res.current == 1) {
            records = res.records;
          } else {
            records = this.records.concat(res.records);
          }

          var loadingMsg = this.loadingMsg;

          if (pageNum == res.pages) {
            loadingMsg = ths.i18n.noMore;
          }

          console.log(res);
          ths.setData({
            records: records,
            totalPage: res.pages,
            pageNum: pageNum,
            loadingMsg: loadingMsg,
            emptyMsg: ths.i18n.noPromotionProduct
          });
        }
      });
    },

    /**
     * 点击导航菜单
     */
    onTabTouch: function (e) {
      var sort = e.currentTarget.dataset.sort;

      if (sort == this.sort) {
        this.setData({
          orderBy: this.orderBy == 0 ? 1 : 0
        });
        this.loadPageData(1);
      } else {
        this.setData({
          sort: sort,
          orderBy: 1
        });
        this.loadPageData(1);
      }
    },

    /**
     * 获取分销员信息
     */
    getDisInfo () {
      http.request({
        url: "/p/distribution/user/distributionUserInfo",
        method: "GET",
        data: {
          shopId: 1
        },
        callBack: res => {
          if (res.state === -1) {
            this.setData({
              shareShow: false
            });
            uni.showModal({
              title: '',
              showCancel: false,
              content: this.i18n.distributorBanned,
              confirmText: this.i18n.confirm,
              confirmColor: "#eb2444",
              success (res) {
                if (res.confirm) {
                  uni.switchTab({
                    url: '/pages/user/user'
                  })
                }
              }
            })
          }

          if (res.state === 2) {
            this.setData({
              shareShow: false
            });
            uni.showToast({
              title: this.i18n.distributorCleared,
              mask: true,
              icon: 'none'
            })
            uni.showModal({
              title: '',
              cancelText: this.i18n.cancel,
              content: this.i18n.distributorCleared,
              confirmText: this.i18n.confirm,
              confirmColor: "#eb2444",
              success (res) {
                if (res.confirm) {
                  uni.redirectTo({
                    url: '/packageDistribution/pages/apply-dist/apply-dist'
                  })
                } else if (res.cancel) {
                  uni.switchTab({
                    url: '/pages/user/user'
                  })
                }
              }
            })
          }

        }
      })
    },

    /**
     * 名称输入
     */
    onProdNameInput: function (e) {
      this.setData({
        prodName: e.detail.value.trim()
      });
    },

    /**
     * 搜索
     */
    onProdNameSearch: function () {
      // 判断搜索框是否为空
      if (!this.prodName.trim()) {
        uni.showToast({
          title: this.i18n.inpKeyWords,
          icon: 'none',
        })
        return
      }
      this.loadPageData(1);
    },

    /**
     * 生成复制分享链接
     */
    getShareLink: function () {
      //从缓存获取分销员卡号，如果没有则去接口获取，以备转发时使用
      var cardno = wx.getStorageSync("distCardNo");
      if (!cardno) {
        http.request({
          url: "/p/distribution/user/distributionUserInfo",
          method: "GET",
          callBack: res => {
            wx.setStorageSync("distCardNo", res.cardNo);
          }
        });
      }
      this.path = '/pages/prod/prod?prodid=' + this.shareProdId + '&cardno=' + cardno
    },

    /**
     * 显示分享弹窗
     */
    onShowShare: function (e) {
      this.getDisInfo()
      var prodId = e.currentTarget.dataset.prodid;
      var prodName = e.currentTarget.dataset.prodname;
      var pic = e.currentTarget.dataset.pic;
      this.setData({
        shareShow: true,
        shareProdId: prodId,
        shareProdName: prodName,
        sharePic: pic
      }); //从缓存获取分销员卡号，如果没有则去接口获取，以备转发时使用

      var cardno = wx.getStorageSync("distCardNo");

      if (!cardno) {
        http.request({
          url: "/p/distribution/user/distributionUserInfo",
          method: "GET",
          data: {
            shopId: 1
          },
          callBack: res => {
            wx.setStorageSync("distCardNo", res.cardNo);
          }
        });
      }
    },

    /**
     * 关闭分享弹窗
     */
    closeEarn: function () {
      this.setData({
        shareShow: false
      });
    },

    /**
     * 用户点击分享到微信小程序
     * @param {Object} sharedata 支付需要的参数
     * @param {Object} cb 成功回调
     * @param {Object} errorCb 失败回调
     */
    onShareWay () {
      var cardno = wx.getStorageSync("distCardNo");
      // console.log('点击微信分享，cardno：',cardno, '//','shareProdId：',this.shareProdId)
      var sharedata = {
        title: this.shareProdName, // 分享标题
        imgUrl: this.sharePic, // 分享图标
        link: config.domainAddress + '/pages/prod/prod?prodid=' + this.shareProdId + '&cardno=' + cardno, // 分享链接
        desc: this.i18n.shartTips, // 分享描述
        type: '', // 分享类型,music、video或link，不填默认为link
        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
      };
      console.log('这是sharedata：', sharedata)
      Wechat.callWexinShare(sharedata, () => {
        this.shareShow = false
        this.guideShare = true
      }, (failMsg) => {
        console.log(failMsg)
      })
    },

    /**
     * 生成小程序二维码
     */
    genWeixinCode () {
      var cardNo = wx.getStorageSync("distCardNo");
      var content = JSON.stringify({
        shareProdId: this.shareProdId,
        cardNo: cardNo
      });

      // #ifdef H5 || APP-PLUS
      let code = `${config.domainAddress}/pages/prod/prod?prodid=${this.shareProdId}&cardno=${cardNo}`
      this.shareWxCode = Qr.createQrCodeImg(code, { size: 250 });
      this.wxCodeShow = true;
      this.shareShow = false
      // #endif

      let params = {
        url: "/qrcodeTicket/miniQrCode",
        method: "GET",
        responseType: 'arraybuffer',
        data: {
          content: content,
          type: 2
        },
        callBack: res => {
          // 微信小程序
          this.setData({
            wxCodeShow: true,
            shareShow: false,
            shareWxCode: "data:image/jpg;base64," + wx.arrayBufferToBase64(res)
          });
        }
      }

      // #ifdef MP-WEIXIN
      http.request(params);
      // #endif
    },

    /**
     * 关闭二维码弹窗
     */
    closeCodePopup () {
      this.setData({
        wxCodeShow: false
      });
    },

    /**
     * 保存图片至相册
     */
    downloadImg () {
      uni.showLoading({
        mask: true
      })
      // #ifdef APP-PLUS
      const bitmap = new plus.nativeObj.Bitmap('test')
      bitmap.loadBase64Data(
        this.shareWxCode,
        () => {
          const url = '_doc/' + new Date() + '.png'; // url建议用时间戳命名方式
          bitmap.save(
            url,
            {
              overwrite: true
            },
            i => {
              uni.saveImageToPhotosAlbum({
                filePath: url,
                success: () => {
                  uni.hideLoading()
                  this.wxCodeShow = false
                  uni.showToast({
                    title: this.i18n.downloadComplete,
                  })
                  bitmap.clear()
                }
              })
            },
            e => {
              uni.hideLoading()
              // alert('保存失败1111', JSON.stringify(e))
              bitmap.clear()
            }
          )
        },
        e => {
          // alert('保存失败2222', JSON.stringify(e))
          uni.hideLoading()
          bitmap.clear()
        }
      )
      // #endif
      // #ifdef MP-WEIXIN
      var cardno = wx.getStorageSync("distCardNo")
      wx.downloadFile({
        header: {
          'Authorization': wx.getStorageSync('token')
        },
        url: config.domain + "/p/distribution/qrCode/invitation?page=pages/prod/prod&scene=" + this.shareProdId + ',' +
          cardno,
        success: (res) => {
          uni.hideLoading()
          //图片保存到本地
          wx.getSetting({
            success: settingData => {
              let flag = settingData.authSetting['scope.writePhotosAlbum']
              if (flag === true || flag === undefined) {
                uni.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: data => {
                    this.wxCodeShow = false
                    uni.showToast({
                      title: this.i18n.downloadComplete,
                      icon: 'success',
                      duration: 2000
                    })
                  },
                  fail: err => {
                    uni.showToast({
                      title: this.i18n.failedSaveTips,
                      icon: 'none',
                      duration: 2000
                    })
                  }
                })
              } else {
                wx.openSetting({
                  success: settingData => {
                    if (settingData.authSetting['scope.writePhotosAlbum']) {
                      uni.showToast({
                        title: this.i18n.failedSave,
                        icon: 'none',
                        duration: 2000
                      })
                    } else {
                      uni.showToast({
                        title: this.i18n.failedSaveTips,
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  }
                })
              }
            }
          })
        }
      })
      // #endif
    }
  }
};
</script>
<style>
@import "./promotion-prod.css";
</style>
